package com.elitel.frame.base.controller;

import com.elitel.common.utils.XCommonUtils;
import com.elitel.frame.base.component.quartz.QuartzScheduler;
import com.elitel.frame.base.component.quartz.SearchServiceTask;
import com.elitel.frame.base.service.*;
import com.elitel.frame.business.service.TreeConfigService;
import com.elitel.frame.main.dao.ext.DbSearchMap;
import com.elitel.frame.main.entity.BaseServices;
import com.elitel.frame.main.entity.SysPrjservice;
import com.elitel.frame.main.entity.ext.PrjServiceExt;
import com.elitel.frame.main.entity.vo.JsonResult;
import com.elitel.frame.main.entity.vo.PageRequestVo;
import com.elitel.frame.main.entity.vo.PageResponseVo;
import com.elitel.frame.main.entity.vo.ZTreeDataModelVo;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Arrays;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/system/sysprjService")
public class SysPrjServiceController {
    private static final Logger logger = LoggerFactory.getLogger(SysPrjServiceController.class);

    @Autowired
    private SysPrjServiceService sysPrjServiceService;
    @Autowired
    private SysProjectService sysProjectService;
    @Autowired
    private BaseServicesService baseServicesService;
    @Autowired
    private CfgExtendService cfgExtendService;
    @Autowired
    private CfgExtmasterService cfgExtmasterService;
    @Autowired
    private DBServerService dBServerService;
    @Autowired
    private TreeConfigService treeConfigService;
    @Autowired
    private TreeConfigFileService treeConfigFileService;
    @Autowired
    private CfgExtreportService cfgExtreportService;
    @Autowired
    private CfgEditService cfgEditService;
    @Autowired
    private CfgExtsearchService cfgExtsearchService;
    @Autowired
    private SearchServiceTask searchServiceTask;
    @Autowired
    private SysDocumentService sysDocumentService;
    @Autowired
    private QuartzScheduler quartzScheduler;
    @Autowired
    private CfgMoreJoinService cfgMoreJoinService;
    @Autowired
    private PolymService polymService;
    @Autowired
    private CfgFileParamService fileParamService;

    /**
     * <pre>getProjectTreeList(获取项目列表)
     * @author：FanWenquan
     * @date：2017年11月21日 下午4:40:27
     * @return</pre>
     */
    @RequestMapping("/getProjectList")
    @ResponseBody
    public Object getProjectTreeList() {
        List<ZTreeDataModelVo> list = sysProjectService.getProjectTreeList();
        return list;
    }

    /**
     * <pre>getProjectConfigData(分页查询服务功能信息)
     * @author：FanWenquan
     * @date：2017年11月21日 下午4:07:12
     * @param pageNo
     * @param pageSize
     * @param seachTxt
     * @return</pre>
     */
    @RequestMapping("/getPrjServiceData")
    @ResponseBody
    public Object getPrjServiceData(String pageNo,
                                    String pageSize,
                                    String seachTxt,
                                    String servicename,
                                    String appName,
                                    String servertype,
                                    String pcode,
                                    String servicecode,
                                    String databaseId,
                                    String sysDataLabelId,
                                    String projectname,
                                    String code,
                                    String sortField,
                                    String sortOrder) {
        JsonResult jr = new JsonResult();
        try {
            PageRequestVo<SysPrjservice> pr = new PageRequestVo<SysPrjservice>();
            pr.setSearchContent(seachTxt);
            pr.setServicename(servicename);
            pr.setPageNo(Integer.valueOf(pageNo));
            pr.setPageSize(Integer.valueOf(pageSize));
            pr.setTreeCode(pcode);
            pr.setTreeCodes(Arrays.asList(pcode.split(",")));
            pr.setServertype(servertype);
            pr.setServicetype(servicecode);
            pr.setProjectname(projectname);
            pr.setDatabaseId(databaseId);
            pr.setSysDataLabelId(sysDataLabelId);
            pr.setAppName(appName);
            pr.setCode(code);
            pr.setSortField(sortField);
            pr.setSortOrder("descending".equals(sortOrder) ? "desc" : "asc");
            PageResponseVo<SysPrjservice> pagelist = sysPrjServiceService.getSysProjectServiceList(pr);
            jr.setData(pagelist);
            jr.setSuccess(true);
        } catch (Exception e) {
            jr.setSuccess(false);
            jr.setMsg("工程服务信息加载异常！");
            logger.error(e.getMessage(), e);
        }
        return jr;
    }

    @RequestMapping("/pagePrjServiceData")
    @ResponseBody
    public Object pagePrjServiceData(Integer pageNo, Integer pageSize, String groupId, String servType, String dataType,
                                     String servName, String dbK, String app, String order, String tbName, Integer status) {
        JsonResult jr = new JsonResult();
        try {
            PageResponseVo<DbSearchMap> pagelist =
                    sysPrjServiceService.pagePrjServiceData(pageNo, pageSize, groupId, servType, dataType,
                            servName, app, dbK, order, tbName, status);
            jr.setData(pagelist);
            jr.setSuccess(true);
        } catch (Exception e) {
            jr.setSuccess(false);
            jr.setMsg("工程服务信息加载异常！");
            logger.error(e.getMessage(), e);
        }
        return jr;
    }

    @RequestMapping("/getCount")
    @ResponseBody
    public Object getCounts(String groupId, String servType, String dataType,
                            String servName, String dbK, String app, String tbName, Integer status) {
        JsonResult jr = new JsonResult();
        try {
            Map<String, Integer> pagelist = sysPrjServiceService.getCounts(groupId, servType, dataType,
                    servName, dbK, app,tbName,status);
            jr.setData(pagelist);
            jr.setSuccess(true);
        } catch (Exception e) {
            jr.setSuccess(false);
            jr.setMsg("统计异常！");
            logger.error(e.getMessage(), e);
        }
        return jr;
    }

    @RequestMapping("/getCount33")
    @ResponseBody
    public Object getCounts333() {

        return sysPrjServiceService.getCounts333();
    }

    /**
     * <pre>getServiceBytype(根据项目和服务类型获取服务)
     * @author：FanWenquan
     * @date：2018年1月8日 上午9:44:41
     * @param pcode
     * @param servertype
     * @return</pre>
     */
    @RequestMapping("/getServiceBytype")
    @ResponseBody
    public Object getServiceBytype(String pcode, String servertype) {
        JsonResult jr = new JsonResult();
        try {
            List<PrjServiceExt> list = sysPrjServiceService.getServiceBytype(pcode, servertype);
            jr.setData(list);
            jr.setSuccess(true);
        } catch (Exception e) {
            jr.setSuccess(false);
            jr.setMsg("服务信息加载异常！");
            logger.error(e.getMessage(), e);
        }
        return jr;
    }

    /**
     * <pre>insertPrjService(添加工程服务)
     * @author：FanWenquan
     * @date：2017年11月21日 下午4:42:16
     * @param sysPrjservice
     * @return</pre>
     */
    @RequestMapping("/insertPrjService")
    @ResponseBody
    public Object insertPrjService(@RequestBody SysPrjservice sysPrjservice) {
        JsonResult jr = new JsonResult();
        try {
            sysPrjServiceService.insertProjectConfig(sysPrjservice);
            jr.setSuccess(true);
            jr.setMsg("工程服务信息添加成功");
        } catch (Exception e) {
            jr.setSuccess(false);
            jr.setMsg("工程服务信息添加异常！");
            logger.error(e.getMessage(), e);
        }

        return jr;
    }

    /**
     * <pre>getPrjServiceByGuid(根据主键获取工程服务)
     * @author：FanWenquan
     * @date：2017年11月21日 下午4:42:38
     * @param guid
     * @return</pre>
     */
    @RequestMapping("/getPrjServiceByGuid")
    @ResponseBody
    public Object getPrjServiceByGuid(String guid) {
        JsonResult jr = new JsonResult();
        try {
            SysPrjservice sysPrjservice = sysPrjServiceService.getProjectConfigByGuid(guid);
            jr.setSuccess(true);
            jr.setData(sysPrjservice);
        } catch (Exception e) {
            jr.setSuccess(false);
            jr.setMsg("获取工程服务信息异常！");
            logger.error(e.getMessage(), e);
        }
        return jr;
    }


    @RequestMapping("/getPrjServiceByCode")
    @ResponseBody
    public Object getPrjServiceByCode(String serviceCode) {
        JsonResult jr = new JsonResult();
        try {
            PrjServiceExt prjServiceExt = sysPrjServiceService.getPrjServiceExt(serviceCode);
            jr.setSuccess(true);
            jr.setData(prjServiceExt);
        } catch (Exception e) {
            jr.setSuccess(false);
            jr.setMsg("获取工程服务信息异常！");
            logger.error(e.getMessage(), e);
        }
        return jr;
    }

    /**
     * <pre>updatePrjService(修改工程服务信息)
     * @author：FanWenquan
     * @date：2017年11月21日 下午4:42:56
     * @param sysPrjservice
     * @return</pre>
     */
    @RequestMapping("/updatePrjService")
    @ResponseBody
    public Object updatePrjService(@RequestBody SysPrjservice sysPrjservice) {
        JsonResult jr = new JsonResult();
        try {
            sysPrjServiceService.updateProjectConfig(sysPrjservice);
            jr.setSuccess(true);
            jr.setMsg("工程服务信息修改成功");
        } catch (Exception e) {
            jr.setSuccess(false);
            jr.setMsg("工程服务信息修改异常！");
            logger.error(e.getMessage(), e);
        }
        return jr;
    }

    /**
     * <pre>deletePrjService(工程服务信息删除异常)
     * @author：FanWenquan
     * @date：2017年11月21日 下午4:44:52
     * @param
     * @return</pre>
     */
    @RequestMapping("/deletePrjService")
    @ResponseBody
    public Object deletePrjService(String guid) {
        JsonResult jr = new JsonResult();
        try {
            if (null != guid && !"".equals(guid)) {
                SysPrjservice prjservice = sysPrjServiceService.getProjectConfigByGuid(guid);
                if (null != prjservice.getServicetype() && !"".equals(prjservice.getServicetype())) {
                    switch (prjservice.getServicetype()) {
                        case "singleTableServer":
                            cfgExtendService.deleteCfgExtendByPrjservice(prjservice);
                            // 清除该服务的任务调度
                            quartzScheduler.deleteJobs(prjservice.getServicecode());
                            break;
                        case "executeSqlServer":
                            dBServerService.deleteexecuteSqlServerByPrjservice(prjservice);
                            break;
                        case "masterConfigServer":
                            cfgExtmasterService.deleteMasterdataByPrjservice(prjservice);
                            break;
                        case "treeconfigServer":
                            treeConfigFileService.deletetreeconfigServerByPrjservice(prjservice);
                            break;
                        case "reportServer":
                            cfgExtreportService.deleteReportServerByPrjservice(prjservice);
                            break;
                        case "tableEditServer":
                            cfgEditService.deleteCfgEditByPrjservice(prjservice);
                            break;
                        case "searchServer":
                            cfgExtsearchService.deleteSearchInfoByprjservices(prjservice);
                            // 移除调度任务
                            searchServiceTask.removeTask(prjservice.getServicecode());
                            break;
                        case "docSearchServer":
                            sysDocumentService.deleteDocInfoByprjservices(prjservice);
                            // 移除调度任务
                            searchServiceTask.removeTask(prjservice.getServicecode());
                            break;
                        case "moreTableServer":
                            sysPrjServiceService.deleteProjectConfig(guid);
                            cfgMoreJoinService.deleteCfgMoreJoinService(prjservice.getServicecode());
                            break;
                    }
                }
                jr.setSuccess(true);
                jr.setMsg("工程服务信息删除成功");
            } else {
                jr.setSuccess(false);
                jr.setMsg("请选择要删除的工程服务信息");
            }
        } catch (Exception e) {
            jr.setSuccess(false);
            jr.setMsg("工程服务信息删除异常！");
            logger.error(e.getMessage(), e);
        }
        return jr;
    }


    /**
     * 根据主键逻辑删除数据
     *
     * @param guidList
     * @return
     */
    @PostMapping("/deletePrjServiceList")
    @ResponseBody
    public Object delByGuids(@RequestBody List<String> guidList) {
        JsonResult jsonResult = new JsonResult();
        try {
            sysPrjServiceService.delByGuids(guidList);
            jsonResult.setSuccess(true);
            jsonResult.setMsg("删除成功");
        } catch (Exception e) {
            jsonResult.setMsg(e.getMessage());
            jsonResult.setSuccess(false);
        }
        return jsonResult;
    }


    /**
     * <pre>deletePrjServiceList(批量删除工程服务信息) (废弃)
     * @param guidList
     * @return
     */
    @Deprecated
    @RequestMapping("/deletePrjServiceList_Deprecated")
    @ResponseBody
    public Object deletePrjServiceList(@RequestBody List<String> guidList) {
        JsonResult jr = new JsonResult();
        try {
            for (String guid : guidList) {
                this.checkBeforeDel(guid);
                if (XCommonUtils.isEmpty(guid))
                    continue;

                SysPrjservice prjservice = sysPrjServiceService.getProjectConfigByGuid(guid);
                if (XCommonUtils.isEmpty(prjservice.getServicetype()))
                    continue;

                switch (prjservice.getServicetype()) {
                    case "singleTableServer":
                        cfgExtendService.deleteCfgExtendByPrjservice(prjservice);
                        // 清除该服务的任务调度
                        quartzScheduler.deleteJobs(prjservice.getServicecode());
                        break;
                    case "executeSqlServer":
                        dBServerService.deleteexecuteSqlServerByPrjservice(prjservice);
                        break;
                    case "masterConfigServer":
                        cfgExtmasterService.deleteMasterdataByPrjservice(prjservice);
                        break;
                    case "treeconfigServer":
                        treeConfigFileService.deletetreeconfigServerByPrjservice(prjservice);
                        break;
                    case "reportServer":
                        cfgExtreportService.deleteReportServerByPrjservice(prjservice);
                        break;
                    case "tableEditServer":
                        cfgEditService.deleteCfgEditByPrjservice(prjservice);
                        break;
                    case "searchServer":
                        cfgExtsearchService.deleteSearchInfoByprjservices(prjservice);
                        // 移除调度任务
                        searchServiceTask.removeTask(prjservice.getServicecode());
                        break;
                    case "docSearchServer":
                        sysDocumentService.deleteDocInfoByprjservices(prjservice);
                        // 移除调度任务
                        searchServiceTask.removeTask(prjservice.getServicecode());
                        break;
                    case "moreTableServer":
                        sysPrjServiceService.deleteProjectConfig(guid);
                        cfgMoreJoinService.deleteCfgMoreJoinService(prjservice.getServicecode());
                        break;
                    case "polymerServer":
                        polymService.delByGuId(guid);
                        break;
                    case "fileServer":
                        fileParamService.delByGuId(guid);
                        break;
                    default:
                }
            }
            jr.setSuccess(true);
            jr.setMsg("工程服务信息删除成功");

        } catch (Exception e) {
            jr.setSuccess(false);
            jr.setMsg(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        return jr;
    }

    private void checkBeforeDel(String guid) {
        SysPrjservice prjservice = sysPrjServiceService.getByServiceGuid(guid);
        String serviceNames = polymService.selectRelByServiceGuid(guid);
        if (StringUtils.isNotEmpty(serviceNames)) {
            throw new RuntimeException("服务【" + prjservice.getServicename() + "】被聚合服务【" + serviceNames + "】绑定了, 无法删除! ");
        }
    }


    /**
     * <pre>getServerType(获取所有服务)
     * @author：FanWenquan
     * @date：2017年11月23日 下午3:06:16
     * @return</pre>
     */
    @RequestMapping("/getServerType")
    @ResponseBody
    public Object getServerType(@RequestBody Map<String, String> param) {
        List<BaseServices> list = null;
        try {
            list = baseServicesService.getAllServices(param.get("notIncludeGuid"));
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return list;
    }

    /**
     * <pre>getServerType(根据主键获取服务)
     * @author：FanWenquan
     * @date：2017年11月23日 下午3:06:35
     * @return</pre>
     */
    @RequestMapping("/getServerByGuid")
    @ResponseBody
    public Object getServerByGuid(String guid) {
        BaseServices service = null;
        try {
            service = baseServicesService.getServerByGuid(guid);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }

        return service;
    }

    @RequestMapping("/getServerByProjctId")
    @ResponseBody
    public Object getServerByProjctId(String pcode) {
        List<PrjServiceExt> list = null;
        try {
            list = sysPrjServiceService.getServerByProjctId(pcode);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }

        return list;
    }


}
